import os
import sys
from optparse import OptionParser
from os.path import join, getsize


def detect_dir(target_dir, left_size, right_size, end_with):
    for root, dirs, files in os.walk(target_dir):
        for file_x in files:
            if file_x.endswith(end_with):
                file_size = getsize(join(root, file_x))
                if left_size < file_size < right_size:
                    print (file_size, join(root, file_x))
        for dir_x in dirs:
            detect_dir(dir_x, left_size, right_size, end_with)


def add_option():
    parser.add_option("-d", "--dir", dest="target_dir", default=None, help="target dir")
    parser.add_option("-l", "--left_size", dest="left_size", default=7000, help="left size")
    parser.add_option("-r", "--right_size", dest="right_size", default=9000, help="right size")
    parser.add_option("-e", "--end_with", dest="end_with", default=".exe", help="end with")


def check_param(target_dir, left_size, right_size, end_with):
    if target_dir is None or not os.path.isdir(target_dir):
        print "dir invalid"
        parser.print_help()
        sys.exit(1)

    if left_size <= 0 or right_size <= 0 or left_size > right_size:
        print "size invalid"
        parser.print_help()
        sys.exit(1)

    if end_with is None or len(end_with) == 0:
        parser.print_help()
        sys.exit(1)


if __name__ == '__main__':
    parser = OptionParser()
    add_option()
    (options, args) = parser.parse_args()
    t_dir = options.target_dir
    l_size = options.left_size
    r_size = options.right_size
    e_with = options.end_with
    check_param(t_dir, l_size, r_size, e_with)

    print "run with:", (t_dir, l_size, r_size, e_with)
    detect_dir(t_dir, l_size, r_size, e_with)
    print "end."
